package com.interceptor;

import com.utils.CurrentUserHolder;
import com.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Date;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取Authorization头
        String authorizationHeader = request.getHeader("Authorization");
        
        // 检查Authorization头是否存在且格式正确
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            try {
                // 提取token
                String token = authorizationHeader.substring(7); // 去掉"Bearer "前缀
                
                try {
                    // 解析token
                    Claims claims = JwtUtils.parseJWT(token);
                    
                    // 验证token是否过期
                    if (claims.getExpiration().before(new Date())) {
                        throw new RuntimeException("Token已过期");
                    }
                    
                    // 从claims中获取用户信息
                    Integer userId = (Integer) claims.get("userId");
                    String username = (String) claims.get("username");
                    String role = (String) claims.get("role");
                    
                    // 将用户信息存储到CurrentUserHolder中
                    CurrentUserHolder.setUserId(userId);
                    CurrentUserHolder.setUsername(username);
                    CurrentUserHolder.setRole(role);
                    
                    // 继续处理请求
                    return true;
                } catch (Exception e) {
                    // Token无效或已过期，返回401错误
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("Invalid or expired token");
                    return false;
                }
            } catch (Exception e) {
                // token验证失败
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.getWriter().write("{\"error\":\"Invalid or expired token\"}");
                return false;
            }
        }
        
        // 没有提供有效的token
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");
        response.getWriter().write("{\"error\":\"Authorization token required\"}");
        return false;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后清除用户信息，防止内存泄漏
        CurrentUserHolder.clear();
    }
}